package jsu.hx.lost.Config;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.hx.lost.Model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        // 1. 从请求头获取Token
        String authHeader = request.getHeader("Authorization");
        String token = null;
        String username = null;
        Long userId = null;
        User.Role role = null;

        try {
            // 2. 验证并提取Token信息
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);

                if (jwtUtil.isTokenValid(token)) {
                    // 3. 解析Token内容
                    userId = jwtUtil.getUserIdFromToken(token);
                    username = jwtUtil.getUsernameFromToken(token);
                    role = jwtUtil.getRoleFromToken(token);
                }
            }

            // 4. 构建权限对象
            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                List<GrantedAuthority> authorities = new ArrayList<>();

                // 添加角色权限（注意 ROLE_ 前缀）
                if (role != null) {
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + role.name()));
                }

                // 5. 创建认证令牌
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(
                                userId,
                                null,
                                authorities);

                // 6. 添加请求详细信息
                authToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request));

                // 7. 设置安全上下文
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        } catch (ExpiredJwtException ex) {
            logger.warn("Token已过期: " + ex.getMessage());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token已过期");
            return;
        } catch (JwtException | IllegalArgumentException ex) {
            logger.error("无效的JWT Token: " + ex.getMessage());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
            return;
        }

        // 8. 继续过滤器链
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 跳过OPTIONS请求和登录/注册接口
        return request.getMethod().equalsIgnoreCase("OPTIONS") ||
                request.getServletPath().startsWith("/auth/login") ||
                request.getServletPath().startsWith("/user/register") ||             request.getServletPath().startsWith("user/admin/register")||
                request.getServletPath().startsWith("/uploads/");
    }
}